/*
 * @Author: liu
 * @Date: 2024-04-19 23:23:26
 * @LastEditors: 鱿鱼溪学院
 * @LastEditTime: 2025-04-27 01:35:22
 * @FilePath: \yyx_ser_ts\app\db\index.ts
 * @Description:
 * 天道酬勤
 */
import { Sequelize } from 'sequelize-typescript'
import config from '../config'
import logger, { dbLogger } from '../logger'
import path from 'path'

// 解构环境变量或配置项，确保类型安全
const {
  MYSQL_HOST = config.db.db_host,
  MYSQL_PORT = config.db.db_port,
  MYSQL_USER = config.db.db_user,
  MYSQL_PWD = config.db.db_pwd,
  MYSQL_DB = config.db.db_name
} = process.env

// 确保端口为数字类型，避免类型断言
const port = Number(MYSQL_PORT) || 3306

// 初始化 Sequelize 实例
const seq = new Sequelize(MYSQL_DB as string, MYSQL_USER as string, MYSQL_PWD, {
  host: MYSQL_HOST,
  port,
  dialect: 'mysql',
  logging: (msg) => dbLogger.info(msg), // 记录日志
  modelPaths: [path.join(__dirname, '..', 'model')], // 动态加载模型
  define: {
    timestamps: true // 根据需求决定是否启用时间戳
  }
})

// 数据库初始化函数
const db = async () => {
  try {
    await seq.authenticate()
    logger.info('数据库连接成功！')
    console.log('数据库连接成功！')
  } catch (error) {
    logger.error('数据库连接失败！', error)
    // console.error('数据库连接失败！', error)
    throw new Error('数据库连接失败，请检查配置') // 提供更详细的错误信息
  }
}

// 避免重复调用 seq.authenticate()
export default db

// 可选：数据库同步功能（根据需求启用）
// seq.sync({ alter: true }).then(() => {
//   console.log('数据库同步成功！');
// });
